package com.example.project.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.example.project.core.text.Convert;
import com.example.project.entity.Project;
import com.example.project.entity.ProjectMember;
import com.example.project.entity.ProjectRole;
import com.example.project.mapper.ProjectMemberMapper;
import com.example.project.service.ProjectMemberService;
import com.example.project.service.ProjectRoleService;
import com.example.project.service.ProjectService;
import com.example.project.utils.DateUtils;

/**
 * 项目成员Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-11-27
 */
@Service
public class ProjectMemberServiceImpl extends BaseServiceImpl implements ProjectMemberService {

	@Autowired
	private ProjectMemberMapper projectMemberMapper;
	
	@Autowired
	private ProjectRoleService projectRoleService;
	
	@Autowired
	private ProjectService projectService;

	/**
	 * 查询项目成员
	 * 
	 * @param id 项目成员主键
	 * @return 项目成员
	 */
	@Override
	public ProjectMember selectProjectMemberById(Long id) {
		return projectMemberMapper.selectProjectMemberById(id);
	}

	/**
	 * 查询项目成员列表
	 * 
	 * @param projectMember 项目成员
	 * @return 项目成员
	 */
	@Override
	public List<ProjectMember> selectProjectMemberList(ProjectMember projectMember) {
		return projectMemberMapper.selectProjectMemberList(projectMember);
	}

	/**
	 * 根据项目ID查询项目成员列表
	 * 
	 * @param projectId 项目ID
	 * @return 项目成员集合
	 */
	@Override
	public List<ProjectMember> selectProjectMemberListByProjectId(Long projectId) {
		return projectMemberMapper.selectProjectMemberListByProjectId(projectId);
	}

	/**
	 * 新增项目成员
	 * 
	 * @param projectMember 项目成员
	 * @return 结果
	 */
	@Override
	public int insertProjectMember(ProjectMember projectMember) {
		projectMember.setCreateTime(DateUtils.curLocalDateTime());
		
		// 检查用户是否已在项目中
		int checkUserInProject = projectMemberMapper.checkUserInProject(projectMember.getUserId(), projectMember.getProjectId());
		if (checkUserInProject >= 1) {
			return -1; // 用户已在项目中
		}
		
		// 获取项目负责人角色ID
		Long projectLeaderRoleId = getProjectLeaderRoleId();
		
		// 如果设置的角色是项目负责人
		if (projectLeaderRoleId != null && projectLeaderRoleId.equals(projectMember.getRoleId())) {
			// 检查项目中是否已有项目负责人
			ProjectMember leaderQuery = new ProjectMember();
			leaderQuery.setProjectId(projectMember.getProjectId());
			leaderQuery.setRoleId(projectLeaderRoleId);
			List<ProjectMember> existingLeaders = projectMemberMapper.selectProjectMemberList(leaderQuery);
			
			// 如果已有项目负责人，将其改为项目成员角色
			if (!existingLeaders.isEmpty()) {
				Long projectMemberRoleId = getProjectMemberRoleId();
				if (projectMemberRoleId != null) {
					for (ProjectMember existingLeader : existingLeaders) {
						existingLeader.setRoleId(projectMemberRoleId);
						existingLeader.setUpdateBy(projectMember.getCreateBy());
						existingLeader.setUpdateTime(DateUtils.curLocalDateTime());
						projectMemberMapper.updateProjectMember(existingLeader);
					}
				}
			}
			
			// 更新项目信息中的负责人字段
			Project project = projectService.selectProjectById(projectMember.getProjectId());
			if (project != null) {
				project.setProjectLeader(projectMember.getUserId());
				project.setUpdateBy(projectMember.getCreateBy());
				projectService.updateProject(project);
			}
		}
		
		return projectMemberMapper.insertProjectMember(projectMember);
	}

	/**
	 * 修改项目成员
	 * 
	 * @param projectMember 项目成员
	 * @return 结果
	 */
	@Override
	public int updateProjectMember(ProjectMember projectMember) {
		projectMember.setUpdateTime(DateUtils.curLocalDateTime());
		
		// 获取当前要更新的项目成员信息
		ProjectMember currentMember = projectMemberMapper.selectProjectMemberById(projectMember.getId());
		if (currentMember == null) {
			return 0; // 成员不存在
		}
		
		// 检查是否需要检查用户是否存在（如果用户ID或项目ID发生变化）
		if (!currentMember.getUserId().equals(projectMember.getUserId()) || 
			!currentMember.getProjectId().equals(projectMember.getProjectId())) {
			
			// 检查新用户是否已在项目中（排除当前成员）
			int checkUserInProject = projectMemberMapper.checkUserInProjectExcludeCurrent(
				projectMember.getUserId(), 
				projectMember.getProjectId(), 
				projectMember.getId()
			);
			if (checkUserInProject >= 1) {
				return -1; // 用户已在项目中
			}
		}
		
		// 获取项目负责人角色ID
		Long projectLeaderRoleId = getProjectLeaderRoleId();
		
		// 如果设置的角色是项目负责人
		if (projectLeaderRoleId != null && projectLeaderRoleId.equals(projectMember.getRoleId())) {
			// 检查项目中是否已有项目负责人（排除当前成员）
			ProjectMember leaderQuery = new ProjectMember();
			leaderQuery.setProjectId(projectMember.getProjectId());
			leaderQuery.setRoleId(projectLeaderRoleId);
			List<ProjectMember> existingLeaders = projectMemberMapper.selectProjectMemberList(leaderQuery);
			
			// 如果已有项目负责人且不是当前成员，将其改为项目成员角色
			if (!existingLeaders.isEmpty()) {
				Long projectMemberRoleId = getProjectMemberRoleId();
				if (projectMemberRoleId != null) {
					for (ProjectMember existingLeader : existingLeaders) {
						if (!existingLeader.getId().equals(projectMember.getId())) {
							existingLeader.setRoleId(projectMemberRoleId);
							existingLeader.setUpdateBy(projectMember.getUpdateBy());
							existingLeader.setUpdateTime(DateUtils.curLocalDateTime());
							projectMemberMapper.updateProjectMember(existingLeader);
						}
					}
				}
			}
			
			// 更新项目信息中的负责人字段
			Project project = projectService.selectProjectById(projectMember.getProjectId());
			if (project != null) {
				project.setProjectLeader(projectMember.getUserId());
				project.setUpdateBy(projectMember.getUpdateBy());
				projectService.updateProject(project);
			}
		} else if (projectLeaderRoleId != null && projectLeaderRoleId.equals(currentMember.getRoleId())) {
			// 如果之前是项目负责人，但现在不是，需要更新项目信息中的负责人字段
			Project project = projectService.selectProjectById(projectMember.getProjectId());
			if (project != null && projectMember.getUserId().equals(project.getProjectLeader())) {
				project.setProjectLeader(null); // 清空项目负责人
				project.setUpdateBy(projectMember.getUpdateBy());
				projectService.updateProject(project);
			}
		}
		
		return projectMemberMapper.updateProjectMember(projectMember);
	}

	/**
	 * 批量删除项目成员
	 * 
	 * @param ids 需要删除的项目成员主键
	 * @return 结果
	 */
	@Override
	public int deleteProjectMemberByIds(String ids) {
		return projectMemberMapper.deleteProjectMemberByIds(Convert.toStrArray(ids));
	}

	/**
	 * 删除项目成员信息
	 * 
	 * @param id 项目成员主键
	 * @return 结果
	 */
	@Override
	public int deleteProjectMemberById(Long id) {
		return projectMemberMapper.deleteProjectMemberById(id);
	}

	/**
	 * 获取项目负责人角色ID
	 * 
	 * @return 项目负责人角色ID，如果未找到返回null
	 */
	private Long getProjectLeaderRoleId() {
		List<ProjectRole> roleList = projectRoleService.selectAllList();
		for (ProjectRole role : roleList) {
			if ("project_admin".equals(role.getCode())) {
				return role.getId();
			}
		}
		return null;
	}

	/**
	 * 获取项目成员角色ID
	 * 
	 * @return 项目成员角色ID，如果未找到返回null
	 */
	private Long getProjectMemberRoleId() {
		List<ProjectRole> roleList = projectRoleService.selectAllList();
		for (ProjectRole role : roleList) {
			if ("project_member".equals(role.getCode())) {
				return role.getId();
			}
		}
		return null;
	}

	/**
	 * 检查用户是否已在项目中
	 * 
	 * @param userId 用户ID
	 * @param projectId 项目ID
	 * @return 存在数量
	 */
	@Override
	public int checkUserInProject(Long userId, Long projectId) {
		return projectMemberMapper.checkUserInProject(userId, projectId);
	}

	/**
	 * 根据用户ID查询项目成员列表
	 * 
	 * @param userId 用户ID
	 * @return 项目成员集合
	 */
	@Override
	public List<ProjectMember> selectProjectMemberListByUserId(Long userId) {
		return projectMemberMapper.selectProjectMemberListByUserId(userId);
	}

	/**
	 * 统计项目成员数量
	 * 
	 * @param projectId 项目ID
	 * @return 成员数量
	 */
	@Override
	public Integer selectCountByProjectId(Long projectId) {
		return projectMemberMapper.selectCountByProjectId(projectId);
	}
}